package com.banmoon.wait;

import cn.hutool.core.util.StrUtil;

import java.util.LinkedList;
import java.util.Queue;

public class Demo2 {

    public static void main(String[] args) throws InterruptedException {
        Container container = new Container();
        new Thread(new Consumer(container)).start();
        Thread.sleep(1000);
        new Thread(new Producer(container)).start();
    }

}

/**
 * 生产者
 */
class Producer implements Runnable{
    private Container container;

    public Producer(Container container) {
        this.container = container;
    }

    @Override
    public void run() {
        int i = 0;
        while (true){
            try {
                container.put(i);
                System.out.println(StrUtil.format("生产者：生产了{}，当前数量：{}", i, container.queue.size()));
                i++;
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 消费者
 */
class Consumer implements Runnable{
    private Container container;

    public Consumer(Container container) {
        this.container = container;
    }

    @Override
    public void run() {
        while (true){
            try {
                Integer i = container.get();
                System.out.println("消费者：消费了" + i);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 容器
 */
class Container{
    public Queue<Integer> queue;
    public int MAX_SIZE = 10;

    public Container() {
        this.queue = new LinkedList<>();
    }

    public synchronized Integer get(){
        try {
            if(queue.size()==0){
                notifyAll();
                wait();
            }
            return this.queue.poll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public synchronized void put(Integer integer){
        try {
            if(queue.size()>=MAX_SIZE){
                notifyAll();
                wait();
            }
            this.queue.add(integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}